<template>
  <div>
    <el-upload :action=url list-type="picture-card" :on-preview="handlePictureCardPreview"
               :on-remove="handleRemove" :headers="headers" :data="data"
               :before-upload="beforeUpload" :on-success="handleSuccess" :before-remove="beforeRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <!--图片预览-->
    <el-dialog :visible.sync="imageDialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // *****图片上传请求头部*******
      url: '',
      headers: {},
      data: {},
      // 上传图片对话框
      dialogImageUrl: '',
      imageDialogVisible: false
    }
  },
  created () {
    this.url = this.$config.urls.get('author_material')
    this.headers.Authorization = sessionStorage.getItem('TOKEN_KEY')
    this.data.equipmentid = sessionStorage.getItem('EQUIPMENTID_KEY')
  },
  // DOM对象加载完成时
  mounted () {
  },
  methods: {
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.imageDialogVisible = true
    },
    // 文件列表移除文件时的钩子
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    // 上传文件之前的钩子，判断文件是否大于2m
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 文件上传成功时的钩子
    handleSuccess (res, file) {
      console.log(res)
      if (res.code !== 0) {
        console.log(res.error_message)
      } else {
        var content = '<img src="' + res.data.url + '" alt="">'
        // 给富文本加上图片地址
        this.$emit('uploadCallBack', content)
        this.myValue += content
      }
    },
    // 文件上传失败时的钩子
    handleUploadError (err, file, fileList) {
      console.log(err)
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  },
  computed: {},
  name: 'uploadPicture',
  components: {}
}
</script>

<style lang="less" scoped>

</style>
